package org.xfy.ymcc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.xfy.common.constant.Constants;
import org.xfy.common.result.JsonResult;
import org.xfy.ymcc.domain.CourseType;
import org.xfy.ymcc.dto.CourseTypeCrumbsVo;
import org.xfy.ymcc.mapper.CourseTypeMapper;
import org.xfy.ymcc.service.ICourseTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author xfy
 * @since 2023-12-01
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public JsonResult treeData() {
        Object o = redisTemplate.opsForValue().get(Constants.COURSETYPE_TREE);
        if(o!=null){
            return JsonResult.success().setData(o);
        }
        //构建树
        List<CourseType> list = super.list();
        List<CourseType> top = list.stream().filter(courseType -> courseType.getPid() == 0).collect(Collectors.toList());
        Map<Long, CourseType> map = list.stream().collect(Collectors.toMap(CourseType::getId, item -> item, (Key1, key2) -> Key1));
        list.stream().filter(type->type.getPid()!=0).forEach(type->{
            //找到自己的父id
            Long pid = type.getPid();
            //从map中找到父Id的
            CourseType courseType = map.get(pid);
            //将自己加入到父id
            courseType.getChildren().add(type);
        });
        redisTemplate.opsForValue().set(Constants.COURSETYPE_TREE,top);
        return JsonResult.success().setData(top);
    }

    @Override
    public JsonResult loadCrumbs(Long courseTypeId) {
        List<CourseTypeCrumbsVo> crumbsVos = new ArrayList<>();
        //构造面包屑
        CourseType byId = super.getById(courseTypeId);
        String path = byId.getPath();
        //得到族谱
        String[] split = path.split("\\.");
        for (String Pid : split) {
            CourseTypeCrumbsVo courseTypeCrumbsVo = new CourseTypeCrumbsVo();
            //先找到自己
            CourseType my = super.getById(Pid);
            courseTypeCrumbsVo.setCurrent(my);
            List<CourseType> list = super.list(new LambdaQueryWrapper<CourseType>().eq(CourseType::getPid, my.getPid()));
            courseTypeCrumbsVo.setBrothers(list);
            crumbsVos.add(courseTypeCrumbsVo);
        }
        return JsonResult.success().setData(crumbsVos);
    }

}
